package com.seecen.server.intercept;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

public class TokenIntercept implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public TokenIntercept(RedisTemplate<String,String> redisTemplate){
        this.redisTemplate= redisTemplate;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler){
        if(handler instanceof HandlerMethod) {
            // 尝试获取用户的token
            String token = request.getHeader("token");
            if (token == null || "".equals(token)) {
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                return false;
            }
            // 判断如果过期了
            if (!redisTemplate.hasKey(token)) {
                response.setStatus(HttpStatus.FORBIDDEN.value());
                return false;
            } else {
                String value = (String) redisTemplate.opsForValue().get(token);
                // 刷新token存储时间
                redisTemplate.opsForValue().set(token, value, 30, TimeUnit.SECONDS);
            }
        }
        // 通过拦截，给予放行
        return true;
    }
}
